<?php


namespace App\Http\Controllers\Asset;


trait AssetFindOrNewPivotTrait
{

    protected function getOrNewPivot(string $pivotName)
    {
        $pivotId = request()->get($pivotName . '_id');
        $pivotBean = request()->get($pivotName);
        // for location/vendor it is optional
        if (in_array($pivotName, ['location', 'vendor']) && empty($pivotBean)) {
            return null;
        }
        if (!empty($pivotId)) {
            return $pivotId;
        }
        // create new pivot and return the id
        $model = 'App\Models\Asset' . ucfirst($pivotName);
        $instance = new $model();
        $instance->name = $pivotBean;
        $instance->save();
        return $instance->id;
    }
}